<?php

class SiteController extends Controller {

    /**
     * Declares class-based actions.
     */
    public function renderItem($id) {
        $this->layout = false;
        //Get event language
        $event = Translate::model()->with('event')->find('event_id=' . $id);
        $time  = date("H:i / d-m-Y",strtotime($event->event['start_date'].$event->event['start_time']));
        //Get gallery
        $gallery = Gallery::model()->with('items')->findByPk($event->event->gallery_id);
        //Get cover image for facebook
        $cover_image_face = Item::model()->findByAttributes(array('gallery_id' => $gallery->id, 'cover_image' => 1));
        // Get Main Event
        $main_event = Event::model()->with('tickets')->findByPk($event->event->id);
        //Format video link
        $main_event['video_link'] = MyFunctionCustom::getLinkYoutube($main_event['video_link']);
        //facebook comment
       //Yii::app()->clientScript->registerMetaTag($event['main_title'], $event['main_title'], $event['main_title'], array('id' => 'meta_og_title', 'property' => 'og:title'));
        //Yii::app()->clientScript->registerMetaTag(Yii::app()->baseUrl . '/data/image/event/' . $cover_image_face['name'], '', null, array('id' => 'meta_og_image', 'property' => 'og:image'));
        //Yii::app()->clientScript->registerMetaTag('mogsn', $time, $time, array('id' => 'meta_og_site_name', 'property' => 'og:site_name'));
        //Yii::app()->clientScript->registerMetaTag($event['sub_title'] . ' <br /> ' . $time,$event['sub_title'] . ' <br /> ' . $time, $event['sub_title'] . ' <br /> ' . $time, array('id' => 'meta_og_description', 'property' => 'og:description'));
        // var_dump($main_event['tickets']);die();
        //Render views with AJAX load without return json
        $this->render('views', array(
            'event' => $event,
            'gallery' => $gallery,
            'main_event' => $main_event
        ));
    }

    public function actions() {
        return array(
            // captcha action renders the CAPTCHA image displayed on the contact page
            'captcha' => array(
                'class' => 'CCaptchaAction',
                'backColor' => 0xFFFFFF,
            ),
            // page action renders "static" pages stored under 'protected/views/site/pages'
            // They can be accessed via: index.php?r=site/page&view=FileName
            'page' => array(
                'class' => 'CViewAction',
            ),
        );
    }
   
    /**
     * <Jason>
     * <Email: pmhai90@gmail.com>
     */
    public function actionSearch($q = '') {
        if (isset(Yii::app()->session['_lang'])) {
            $language = Yii::app()->session['_lang'];
        } else {
            Yii::app()->session['_lang'] = 'vi';
            $language = Yii::app()->session['_lang'];
        }
        date_default_timezone_set('UTC');
        $start_date = date('Y-m-d', time());
        // Get Current Language
        $languages = Language::model()->findByAttributes(array('language_code' => $language));

        //Events
        $str_return = '';
        if ($q != '') {
            $str = MyFunctionCustom::remove_vietnamese_accents($q);
            $str_return = strtolower($str);
        }
        $criteria = new CDbCriteria();
        $criteria->select = '*';
        $criteria->with = 'event';
        $criteria->join = 'JOIN events e ON t.event_id = e.id';
        $criteria->compare('t.language_id', $languages->id);
        $criteria->compare('e.start_date', '>=' . $start_date);
        $criteria->compare('e.active_status', STATUS_ACTIVE);
        $criteria->addCondition('t.main_title like "%' . $str_return . '%" OR t.sub_title like "%' . $str_return . '%" OR t.description like "%' . $str_return . '%" OR t.location like "%' . $str_return . '%" OR t.address like "%' . $str_return . '%"');
        $event = Translate::model()->findAll($criteria);
        //Get all item from gallery of an event
        foreach ($event as $key => $value) {
            $image = Item::model()->findByAttributes(array('gallery_id' => $value->event->gallery_id, 'cover_image' => 1));
            //Assign cover image
            if ($image != null) {
                $value['event']['cover_image'] = $image->name;
            }
        }
        $this->render('index', array('data' => $event));
    }

    /**
     * This is the default 'index' action that is invoked
     * when an action is not explicitly requested by users.
     */
    public function actionIndex() {
        // renders the view file 'protected/views/site/index.php'
        // using the default layout 'protected/views/layouts/main.php'
        // var_dump($_POST);die();
        if (isset(Yii::app()->session['_lang'])) {
            $language = Yii::app()->session['_lang'];
        } else {
            Yii::app()->session['_lang'] = 'vi';
            $language = Yii::app()->session['_lang'];
        }
        if (isset($_POST['Event']['date'])){


            $start_date = date('Y-m-d', strtotime($_POST['Event']['date']));
            // var_dump($start_date);die();
            // Get Current Language
            $languages = Language::model()->findByAttributes(array('language_code' => $language));
            //Define new Criteria
            $criteria = new CDbCriteria();
            $criteria->select = '*';
            $criteria->with = 'event';
            $criteria->join = 'JOIN events e ON t.event_id = e.id INNER JOIN event_categories c ON e.category_id = c.id';
            $criteria->compare('t.language_id', $languages->id);
            $criteria->compare('e.start_date', $start_date);
            $criteria->compare('e.active_status', STATUS_ACTIVE);
            $criteria2 = new CDbCriteria();
            $criteria2->condition = 't.language_id = :lang_id AND e.start_date >= :start_date AND e.priority IS NOT NULL';
            $criteria2->params = array(':lang_id' => $languages->id,':start_date' => $start_date);
            // $criteria->order = 'e.priority DESC';
            $criteria->order = 'e.priority DESC , e.start_date,e.start_time,t.main_title ASC';
            $criteria->mergeWith($criteria2, 'OR');
            $event = Translate::model()->findAll($criteria);
            //Get all item from gallery of an event
            foreach ($event as $key => $value) {
                $image = Item::model()->findByAttributes(array('gallery_id' => $value->event->gallery_id, 'cover_image' => 1));
                //Assign cover image
                if ($image != null) {
                    $value['event']['cover_image'] = $image->name;
                }
            }
        }
        else{
            date_default_timezone_set('UTC');
            $start_date = date('Y-m-d', time());
            // var_dump($start_date);die();
            // Get Current Language
            $languages = Language::model()->findByAttributes(array('language_code' => $language));
            //Define new Criteria
            $criteria = new CDbCriteria();
            $criteria->select = '*';
            $criteria->with = 'event';
            $criteria->join = 'JOIN events e ON t.event_id = e.id INNER JOIN event_categories c ON e.category_id = c.id';

            $criteria->compare('t.language_id', $languages->id);
            $criteria->compare('e.active_status', STATUS_ACTIVE);
            // $criteria->addCondition('t.language_id = ' . $languages->id . ',e.start_date ='.$start_date .' OR t.language_id ='.$languages->id.',e.priority>0,e.start_date>' . $start_date);
            $criteria->compare('e.start_date', $start_date);
            $criteria2 = new CDbCriteria();
            $criteria2->condition = 't.language_id = :lang_id AND e.start_date >= :start_date AND e.priority IS NOT NULL';
            $criteria2->params = array(':lang_id' => $languages->id,':start_date' => $start_date);
            // $criteria->order = 'e.priority DESC';
            $criteria->order = 'e.priority DESC , e.start_date,e.start_time,t.main_title ASC';
            $criteria->mergeWith($criteria2, 'OR');
            $event = Translate::model()->findAll($criteria);
            //Get all item from gallery of an event
            foreach ($event as $key => $value) {
                $image = Item::model()->findByAttributes(array('gallery_id' => $value->event->gallery_id, 'cover_image' => 1));
                //Assign cover image
                if ($image != null) {
                    $value['event']['cover_image'] = $image->name;
                }
            }
        }
        // foreach ($event as $key => $value) {
        //     if ($value->event->priority != null) {
        //         var_dump($value->event->id);
        //     }
        // }
        // if (count($event) <= 0) {
        //     $c = new CDbCriteria();
        //     $c->with = 'event';
        //     $c->join = 'JOIN events e ON t.event_id = e.id';
        //     $c->compare('t.language_id', $languages->id);
        //     $event = Translate::model()->findAll($c);

        //     foreach ($event as $key => $value) {
        //         $image = Item::model()->findByAttributes(array('gallery_id' => $value->event->gallery_id, 'cover_image' => 1));
        //         //Assign cover image
        //         if ($image != null) {
        //         $value['event']['cover_image'] = $image->name;
        //         }
        //     }
        // }

        $this->render('index', array('data' => $event,'date' => $start_date));
    }

    /**
     * This is the action to handle external exceptions.
     */
    public function actionError() {
        if ($error = Yii::app()->errorHandler->error) {
            if (Yii::app()->request->isAjaxRequest)
                echo $error['message'];
            else
                $this->render('error', $error);
        }
    }
    /**
     * This is the action to handle external exceptions.
     */
    public function actionOrder() {
        $arg=  explode('_',  $_GET['transactionID']);
        $orderId=$arg[0];

        $order = Booked::model()->findByPk($orderId);

        if(Pay123::checkResult($order)){
            $order->payment_status=1;
            $order->save();
            $order->createTicket();
            //SendEmail::sendMailBarcode($order);
        }
        Yii::app()->session['order_process'] =   $orderId;
        $this->redirect(Yii::app()->homeUrl);
    }

    /**
     * Displays the contact page
     */
    public function actionContact() {
        $model = new ContactForm;
        if (isset($_POST['contact'])) {
            $model->attributes = $_POST['contact'];
               
               //CmsEmail::sendmail(1, $subject, $model->body, Yii::app()->params['adminEmail'], $model->email,'');
               
                $data = array(
            'subject'=>$model->subject,
            'params'=>array(
                'message'=>$model->body,
            ),
//            'view'=>'message',
            'to'=>Yii::app()->params['adminEmail'],
            'from'=> $model->email
        );
         CmsEmail::mail($data);
                echo Yii::t('lang', 'contact_success');
        }
        die;
        //$this->render('contact', array('model' => $model));
    }

    /**
     * Displays the login page
     */
    public function actionLogin() {
        $model = new LoginForm;

        // if it is ajax validation request
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'login-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }

        // collect user input data
        if (isset($_POST['LoginForm'])) {
            $model->attributes = $_POST['LoginForm'];
            // validate user input and redirect to the previous page if valid
            if ($model->validate() && $model->login())
                $this->redirect(Yii::app()->user->returnUrl);
        }
        // display the login form
        $this->render('login', array('model' => $model));
    }

    /**
     * Logs out the current user and redirect to homepage.
     */
    public function actionLogout() {
        Yii::app()->user->logout();
        $this->redirect(Yii::app()->homeUrl);
    }

    public function actionfblogin() {
        try {
            $facebook_id = Yii::app()->facebook->getUser();
            if ((int) ($facebook_id) == 0)
                $this->redirect(MyFunctionCustom::getFacebookLoginUrl());
            $statusOk = MyFunctionCustom::saveUserFacebook();
            if (!$statusOk)
                $this->redirect(Yii::app()->createAbsoluteUrl('site/accountsuspend'));
            $session = Yii::app()->session;
            if (isset($session['FACEBOOK_REDIRECT_URI']))
                $this->redirect($session['FACEBOOK_REDIRECT_URI']);
            $this->redirect(Yii::app()->createAbsoluteUrl('site/index'));
        } catch (Exception $exc) {
            echo $exc->getMessage();
            die;
        }
    }

    public function actionAccountsuspend() {
        $this->render('suspend');
    }

    public function actionEventdate() {
        if (isset(Yii::app()->session['_lang'])) {
            $language = Yii::app()->session['_lang'];
        } else {
            Yii::app()->session['_lang'] = 'vi';
            $language = Yii::app()->session['_lang'];
        }

        if (isset($_POST['Event']['date'])) {
            //Format date
            $start_date = date('Y-m-d', strtotime($_POST['Event']['date']));
            // var_dump($start_date);die();
            // Get Current Language
            $languages = Language::model()->findByAttributes(array('language_code' => $language));

            //Define new Criteria
            $criteria = new CDbCriteria();
            $criteria->select = '*';
            $criteria->with = 'event';
            $criteria->join = 'JOIN events e ON t.event_id = e.id INNER JOIN event_categories c ON e.category_id = c.id';
            $criteria->compare('t.language_id', $languages->id);
            $criteria->compare('e.start_date', $start_date);
            $criteria->compare('e.active_status', STATUS_ACTIVE);
            $criteria2 = new CDbCriteria();
            $criteria2->condition = 't.language_id = :lang_id AND e.start_date >= :start_date AND e.priority IS NOT NULL';
            $criteria2->params = array(':lang_id' => $languages->id,':start_date' => $start_date);
            // $criteria->order = 'e.priority DESC';
            $criteria->order = 'e.priority DESC , e.start_date,e.start_time,t.main_title ASC';
            $criteria->mergeWith($criteria2, 'OR');
            $event = Translate::model()->findAll($criteria);
            //Get all item from gallery of an event
            foreach ($event as $key => $value) {
                $image = Item::model()->findByAttributes(array('gallery_id' => $value->event->gallery_id, 'cover_image' => 1));
                //Assign cover image
                if ($image != null) {
                    $value['event']['cover_image'] = $image->name;
                }
            }

            $this->render('index', array('data' => $event,'date' => $start_date));
        } else {
            date_default_timezone_set('UTC');
            $start_date = date('Y-m-d', time());
            // var_dump($start_date);die();
            // Get Current Language
            $languages = Language::model()->findByAttributes(array('language_code' => $language));
            //Define new Criteria
            $criteria = new CDbCriteria();
            $criteria->select = '*';
            $criteria->with = 'event';
            $criteria->join = 'JOIN events e ON t.event_id = e.id INNER JOIN event_categories c ON e.category_id = c.id';
            $criteria->compare('t.language_id', $languages->id);
            $criteria->compare('e.start_date', $start_date);
            $criteria->compare('e.active_status', STATUS_ACTIVE);
            $criteria2 = new CDbCriteria();
            $criteria2->condition = 't.language_id = :lang_id AND e.start_date >= :start_date AND e.priority IS NOT NULL';
            $criteria2->params = array(':lang_id' => $languages->id,':start_date' => $start_date);
            // $criteria->order = 'e.priority DESC';
            $criteria->order = 'e.priority DESC , e.start_date,e.start_time,t.main_title ASC';
            $criteria->mergeWith($criteria2, 'OR');
            $event = Translate::model()->findAll($criteria);
            //Get all item from gallery of an event
            foreach ($event as $key => $value) {
                $image = Item::model()->findByAttributes(array('gallery_id' => $value->event->gallery_id, 'cover_image' => 1));
                //Assign cover image
                if ($image != null) {
                    $value['event']['cover_image'] = $image->name;
                }
            }
            // var_dump($event);die();

            $this->render('index', array('data' => $event,'date' => $start_date));
        }
    }

    public function actionAbout() {
        $this->layout = false;
        $language = Language::model()->findByAttributes(array('language_code' => Yii::app()->language));
        $model = '';
        if ($language) {
            $model = Cms::model()->findByAttributes(array('language_id' => $language->id, 'page_type' => 'about'));
        }
        $this->render('about', array('model' => $model));
    }

    public function actionHelp() {
        $this->layout = false;
        $language = Language::model()->findByAttributes(array('language_code' => Yii::app()->language));
        $model = '';
        if ($language) {
            $model = Cms::model()->findByAttributes(array('language_id' => $language->id, 'page_type' => 'help'));
        }
        $this->render('help', array('model' => $model));
    }

    public function actionRequirelogin() {
        $this->layout = false;
        $facebook_id = Yii::app()->facebook->getUser();
        $statusOk = '';
        $link='';
        if ((int) ($facebook_id) == 0){
            $link = MyFunctionCustom::getFacebookLoginUrlTest();
//             $this->render('requied_login',array('link'=>$link));
        }else{
            $statusOk = MyFunctionCustom::saveUserFacebook();
//           if($statusOk){
//               if(isset(Yii::app()->session['LOGGED_USER'])){
//                   die('<script>
//                       alert("test");
//                            parent.$.fancybox.close();
//                            window.close();
//                        </script>');
//               }
//           }
        }

        $this->render('requied_login',array('link'=>$link,'status'=>$statusOk));
    }

    public function actionBooked($id) {

        $this->layout = FALSE;
        // Load data needed
        $languages = Language::model()->findByAttributes(array('language_code' => Yii::app()->language));
        $model = new Booked();
        $userlogin = Yii::app()->session['LOGGED_USER'];
        $eventTr = Translate::model()->with('event')->findByPk($id);
        $event = Translate::model()->with('event')->findByAttributes(array('language_id' => $languages->id, 'event_id' => $eventTr->event->id));
        $main_event = Event::model()->with('tickets')->findByPk($eventTr->event->id);
        //Check if user is null -- Local only
        if($userlogin == null){
            $user = Users::model()->findByPk(169);
        }else{
            $user = Users::model()->findByPk($userlogin->id);
        }
        //$this->performAjaxValidation($model, 'news-form');
        if (isset($_POST['Booked'])) {
            //Count order booked to generate Ticket Order Number Code
            $criteria = new CDbCriteria();
            $criteria->condition = 'event_id = '.$main_event->id;
            $order_number = Booked::model()->count($criteria);
            // var_dump($_POST['Booked']);die();
            $model->attributes = $_POST['Booked'];
            //Code tested in comment line
            // foreach ($_POST['Booked']['ticket_id'] as $key => $value){
            //     if(isset($_POST['Ticket'])){
            //         $result = array_key_exists($value, $_POST['Ticket']['seat']);
            //         if($result == true){
            //             $seat = $_POST['Ticket']['seat'][$value];
            //         }
            //     }
            //     var_dump($seat);
            // }
            // var_dump($seat);die();
            // var_dump($_POST['Ticket']);die();
            // echo "<pre>";
            // print_r($model->attributes);
            // echo "</pre>";die();



            if ($model->validate()) {
                // Set default time zone for Server Only
                date_default_timezone_set('UTC');
                $model->booked_date = date('Y-m-d');
                $model->booked_time = date('Y-m-d H:i');
                $model->facbook_id = (isset($user->oauth_uid)) ? $user->oauth_uid : NULL;
                $model->event_id = $eventTr['event_id'];
                $model->user_id = (isset($user->id)) ? $user->id : NULL;
                $model->status = STATUS_PENDING;
                
                $model->ticket_order_number = trim($main_event->event_code) . '_TON-' . $order_number++;
                // Field not reference just to test
                $model->ticket_id = $_POST['Booked']['ticket_id'][0];
                $model->quantity = json_encode($_POST['ticket']['quantity']);
                //Check if booked order from customer greater than 500.000 VND
                $total_order =null;
                foreach ($_POST['Booked']['ticket_id'] as $key => $value) {
                    $ticket = Ticket::model()->findByPk($value);
                    foreach ($_POST['ticket']['quantity'] as $k => $v) {
                        if ($value == $k) {
                            $total_order += $v * $ticket->price;
                        }
                    }
                }
                // var_dump($model->payment_type);
                // var_dump($total_order);
                // var_dump($_POST['Booked']);
                // // var_dump(MAXPRICE);die();
                // if ((int)$total_order > MAXPRICE) {
                //     echo "ABC";die();
                // }
                // else{
                //     echo "BEC";die();
                // }
                if ($total_order > MAXPRICE && $model->payment_type == 1) {
                    $message = Yii::t('lang','warning_order');
                    $this->render('booked',array(
                        'model' => $model,
                        'message' => $message,
                        'event' => $main_event,
                        'user' => $userlogin,
                        'main_event_tr' => $event
                        ));
                }else{
                    $model->save();
                    //Insert multi record for table booked details
                    foreach ($_POST['Booked']['ticket_id'] as $key => $value) {

                        $booked_details = new BookedDetail();
                    //Check isset seat map if user input it. Check user tick with ticket type
                        if(isset($_POST['Ticket'])){
                            $result = array_key_exists($value, $_POST['Ticket']['seat']);
                            if($result == true){
                                $seat = $_POST['Ticket']['seat'][$value];
                                $seat_array = $this->multiexplode(array(",",".","|",":",";"," "),$seat);
                                $booked_details->seat = CJSON::encode($seat_array,true);
                            }
                        }
                        $booked_details->booked_id = $model->id;
                        $booked_details->ticket_id = $value;
                        $ticket = Ticket::model()->findByPk($value);
                        foreach ($_POST['ticket']['quantity'] as $k => $v) {
                            if ($value == $k) {
                                $booked_details->quantity = $v;
                                $booked_details->total_price = $v * $ticket->price;
                            }
                        }
                        $booked_details->save();
                    }
                    //Need to confirm with customer for seat in seat map
                    // var_dump($model['ticket_id']);die();
                    Yii::app()->user->setFlash('booked', 'success');
                    // $book = Booked::model()->findAllByAttributes(array('user_id' => $user->id, 'ticket_id' => $model['ticket_id']));
                    // var_dump($book);
                    if($userlogin != null){
                        SendEmail::sendEmailBooksuccess($userlogin, $event, $main_event, $model->id);
                    }
                    else{
                        SendEmail::sendEmailBooksuccess($user, $event, $main_event, $model->id);
                    }
                    $this->render('booked', array(
                        'model' => $model,
                        'event' => $main_event,
                        'user' => $userlogin,
                        'main_event_tr' => $event
                        ));
                    // Yii::app()->user->setFlash('booked', 'thank');
                    Yii::app()->end();
                        // var_dump($model->phone);die();
                    $this->refresh(); 
                }

            }
        }
        $this->render('booked', array(
            'model' => $model,
            'event' => $main_event,
            'user' => $userlogin,
            'main_event_tr' => $event
        ));
    }
    public function multiexplode ($delimiters,$string) {
    
        $ready = str_replace($delimiters, $delimiters[0], $string);
        $launch = explode($delimiters[0], $ready);
        return  $launch;
    }
    public function actionThankyou() {
        $this->render('thankyou');
    }

    public function actionLoadfriendfb($tichket) {
        $this->layout = FALSE;
        $arrAvata = MyFunctionCustom::CheckFriendBookedFbAvata($tichket);
        $this->render('facebook_friend', array('arrAvata' => $arrAvata));
    }

    public function actionMap() {
        $this->layout = FALSE;
        $this->render('map');
    }

    public function actionTestlogin(){
        $this->layout=false;
        $facebook_id = Yii::app()->facebook->getUser();
        $link='';
        if ((int) ($facebook_id) == 0){
            $link = MyFunctionCustom::getFacebookLoginUrlTest();
             $this->render('test',array('link'=>$link));
        }else{
            $statusOk = MyFunctionCustom::saveUserFacebook();
           if($statusOk){
               if(isset(Yii::app()->session['LOGGED_USER'])){
                   die('<script>
                          var curent = window.parent.location.href;
                          parent.window.location=curent;
                           window.close();
                        </script>');
               }
           }
        }
    }
    public function actionLoadfile(){
        $this->layout=false;
        $content = $this->render('load_file');
        echo $content;die;
    }
    public function actionLoadseat(){
        $this->layout=false;
        if(isset($_POST) && $_POST != null){
            parse_str($_POST['data'], $searcharray);
            if(isset($searcharray['ticket'])&& is_array($searcharray['ticket'])){
//                unset($_SESSION['ghe']);die;
                $dataSession = (isset(Yii::app()->session['ghe'])) ? Yii::app()->session['ghe']:array();
                foreach ($searcharray['ticket'] as $k=>$v){
                      $dataSession[$k]=$v;
                }
//                 Yii::app()->session['ghe'] = $dataSession;
//                echo json_encode(Yii::app()->session['ghe']);die;
                Yii::app()->session['ghe'] = $dataSession;
                echo Yii::t('lang','add_success');die;
            }
        }
        $content = $this->render('load_seat');
        echo $content;die;
    }

}